﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;

namespace 语文字帖
{
    /// <summary>
    /// 比赛的成绩
    /// </summary>
    public class ChessResult
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 比赛的年月
        /// </summary>
        public string Yearmonth { get; set; }
        /// <summary>
        /// 比赛的名称
        /// </summary>
        public string MatchName { get; set; }
        /// <summary>
        /// 比赛的组别
        /// </summary>
        public string LevelName { get; set; }
        /// <summary>
        /// 比赛的名称
        /// </summary>
        public int Ranking { get; set; }
    }

    /// <summary>
    /// 比赛查询
    /// </summary>
    public static class ChessQuery
    {
        private static readonly ILog log = LogManager.GetLogger("NETCoreRepository", typeof(string));

        /// <summary>
        /// 查询比赛成绩
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<ChessResult> GetMatchResult(string name)
        {
            List<ChessResult> itemlist = new List<ChessResult>();
            DataSet ds = MysqlHelper.QueryByName(name.Trim());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //matchbegindate, matchname, levelname, ranking, organization
                    itemlist.Add(new ChessResult()
                    {
                        Name = dr["name"] != DBNull.Value ? dr["name"].ToString() : string.Empty,
                        LevelName = dr["levelname"] != DBNull.Value ? dr["levelname"].ToString() : string.Empty,
                        MatchName = dr["matchname"] != DBNull.Value ? dr["matchname"].ToString() : string.Empty,
                        Ranking = dr["ranking"] != DBNull.Value ? int.Parse(dr["ranking"].ToString()) : -1,
                        Yearmonth = dr["matchbegindate"] != DBNull.Value ? dr["matchbegindate"].ToString().Substring(0, 7).Replace("-", string.Empty) : string.Empty
                    }
                    );
                }
                string resultstring = JsonFormatter.ConvertStringToJson(JsonConvert.SerializeObject(itemlist));
                log.InfoFormat("返回的查询结果：\n{0}", resultstring);
                return itemlist;
            }
            else
            {
                log.Info("查询返回了空结果");
                return itemlist;
            }
        }
    }
}
